package com.wbsxch.shiro.controller;

import com.wbsxch.shiro.dto.RoleDTO;
import com.wbsxch.shiro.form.RoleForm;
import com.wbsxch.shiro.service.RoleService;
import com.wbsxch.shiro.vo.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequiresPermissions("add:user")
    @PostMapping("/")
    public String save(@RequestBody RoleForm roleForm){
        RoleDTO roleDTO = new RoleDTO();
        BeanUtils.copyProperties(roleForm,roleDTO);
        roleService.insert(roleDTO);
        return "保存成功";
    }

    @RequiresPermissions("delete:user")
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Long id){
        roleService.delete(id);
        return "删除成功";
    }

    @RequiresPermissions("update:user")
    @PutMapping("/{id}")
    public String update(@RequestBody RoleForm roleForm,@PathVariable Long id){
        RoleDTO roleDTO = new RoleDTO();
        BeanUtils.copyProperties(roleForm,roleDTO);
        roleDTO.setId(id);
        roleService.update(roleDTO);
        return "修改成功";
    }

    @RequiresPermissions("query:user")
    @GetMapping("/")
    public List<RoleVO> query(RoleForm roleForm){
        RoleDTO roleDTO = new RoleDTO();
        BeanUtils.copyProperties(roleForm,roleDTO);
        List<RoleDTO> roleDTOS = roleService.selectAll(roleDTO);
        List<RoleVO> roleVOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(roleDTOS)){
            roleVOS = roleDTOS.stream().map(e -> {
                RoleVO roleVO = new RoleVO();
                BeanUtils.copyProperties(e, roleVO);
                return roleVO;
            }).filter(e -> e != null).collect(Collectors.toList());
        }
        return roleVOS;
    }
}
